package game_config

import (
	"encoding/json"
	"fmt"
	"gorm.io/gorm"
	"os"
	"server_cluster/common/sharedb"
	"strconv"
	"strings"
)

const (
	DBUSER_DEV  = "link:e9aa3d4726db28e9"
	DBUSER_PROD = "link:e9aa3d4726db28e9"
	USER_MAX    = 100
)

var CONF *Config = nil

type Config struct {
	ServerId        int32  `json:"server_id,omitempty"`         // 服务器id
	LogLevel        string `json:"log_level,omitempty"`         // 日志级别
	ShmKey          int32  `json:"shm_key,omitempty"`           // 共享内存标识
	GameHost        string `json:"game_host,omitempty"`         // 服务器监听地址
	DbHost          string `json:"db_host,omitempty"`           // 数据库地址
	DbPool          int32  `json:"db_pool,omitempty"`           // 数据库连接数量
	HttpPort        int32  `json:"http_port,omitempty"`         // http服务端口
	DevEnv          bool   `json:"dev_env,omitempty"`           // 是否为开发环境
	ConfigTablePath string `json:"config_table_path,omitempty"` // 配置表文件路径
	LogSql          bool   `json:"log_sql,omitempty"`           // 是否记录sql日志
}

func (c *Config) GetDbHost() string {
	if c.DevEnv {
		return DBUSER_DEV + c.DbHost
	}
	return DBUSER_PROD + c.DbHost
}

func InitConfig() {
	if len(os.Args) > 1 && os.Args[1] == "config" {
		c := &Config{
			ServerId:        2,
			LogLevel:        "debug",
			ShmKey:          12888,
			GameHost:        "192.168.3.247:12888",
			DbHost:          "@tcp(192.168.3.247:3306)/jgame?charset=utf8mb4&parseTime=true&loc=Local&timeout=10s",
			DbPool:          20,
			HttpPort:        12889,
			DevEnv:          true,
			ConfigTablePath: "./game_data_config",
			LogSql:          false,
		}
		data, err := json.MarshalIndent(c, "", "\t")
		if err != nil {
			panic(err)
		}
		str := string(data)
		str = strings.ReplaceAll(str, "\\u003c", "<")
		str = strings.ReplaceAll(str, "\\u003e", ">")
		str = strings.ReplaceAll(str, "\\u0026", "&")
		err = os.WriteFile("./config.json", []byte(str), 0644)
		if err != nil {
			panic(err)
		}
		os.Exit(0)
	}

	filePath := "./config.json"
	if len(os.Args) > 1 {
		filePath = os.Args[1]
	}
	CONF = new(Config)
	CONF.loadConfigFile(filePath)
}

func (c *Config) RebuildSelf(db *gorm.DB) {
	var configServer = sharedb.Config_server{
		Id: int16(c.ServerId),
	}
	err := configServer.GetOneByModel(db)
	if err != nil {
		panic(err)
	}
	c.ShmKey = configServer.Port
	c.GameHost = "0.0.0.0:" + strconv.Itoa(int(configServer.Port))
	c.LogLevel = configServer.LogLevel
	c.HttpPort = configServer.HttpPort
	c.DevEnv = configServer.DevEnv
	c.LogSql = configServer.LogSql
	c.Write2File()
}

func (c *Config) Write2File() {
	filePath := "./config.json"
	if len(os.Args) > 1 {
		filePath = os.Args[1]
	}
	data, err := json.MarshalIndent(c, "", "\t")
	if err != nil {
		panic(err)
	}
	str := string(data)
	str = strings.ReplaceAll(str, "\\u003c", "<")
	str = strings.ReplaceAll(str, "\\u003e", ">")
	str = strings.ReplaceAll(str, "\\u0026", "&")
	err = os.WriteFile(filePath, []byte(str), 0644)
	if err != nil {
		panic(err)
	}
}

func GetConfig() *Config {
	return CONF
}

func (c *Config) loadConfigFile(filePath string) {
	data, err := os.ReadFile(filePath)
	if err != nil {
		info := fmt.Sprintf("config file load error: %v\n", err)
		panic(info)
	}
	err = json.Unmarshal(data, c)
	if err != nil {
		info := fmt.Sprintf("config file parse error: %v\n", err)
		panic(info)
	}
}
